<?php

namespace app\common\service;

use app\common\service\traits\InstanceTrait;
use app\model\site\User;
use app\model\site\UserLevel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;


class CommonUserService
{

    use InstanceTrait;


    /**
     * 更新会员等级（升级/降级）
     * @param User $user
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function updateLevel(User $user){
        $growth = $user->growth;    // 会员的当前成长值
        $userLevelId = $user->level_id;
        // 按会员等级进行降序排列
        $levels = UserLevel::where('site_id', $user->site_id)->where('is_show',1)->order('grade desc')->select();
        foreach ($levels as $vo){
            if ($growth  >= $vo->growth && $userLevelId != $vo->id){   // 符合成长值条件的最高等级， 并且会员不属于当前等级（断言小于）
                // 升级会员
                $user->level_id = $vo->id;
                $user->save();
                // 跳出循环
                break;
            }
        }

    }

}
